#include "qrng.h"
#include <string.h>

#ifndef _WIN32
#include <dlfcn.h>
#include <unistd.h>
#include <sys/time.h>
#else
#include <windows.h>
#endif

#define RANDOMBYTES 1048576
PSKF_FUNCLIST FunctionList;

int load_library()
{
	int ret = 0;
	void * lib_handle = NULL;
	char  path[128] = {0};

#ifdef _WIN32
	P_SKF_GetFuncList GetFunction = NULL;
	GetCurrentDirectory(MAX_PATH, path);
	strcat(path, "\\SKF.dll");
	printf("Load Dll %s\n", path);
	lib_handle = LoadLibrary(path);
	if (lib_handle==NULL)
	{
		ret = GetLastError();
		printf("Load Dll Fail:%d\n", ret);
		return ret;
	}
	else
	{
		GetFunction = (P_SKF_GetFuncList)GetProcAddress(lib_handle, "SKF_GetFuncList");
		if (GetFunction == NULL)
		{
			ret = GetLastError();
			return ret;
		}
		printf("Load Dll OK\n");
		ret = GetFunction(&FunctionList);
		if (ret) return ret;
	}
#else
	P_SKF_GetFuncList get_func_list;

    getcwd(path, sizeof(path));
    strcat(path, "/libskf.so");
	lib_handle = dlopen(path, RTLD_LAZY );
	if (!lib_handle)
	{
		printf("Open Error:%s.\n", dlerror());
		return 0;
	}

	get_func_list = dlsym(lib_handle, "SKF_GetFuncList");
	if (get_func_list == NULL)
	{
		printf("Dlsym Error:%s.\n", dlerror());
		return 0;
	}

	ret = get_func_list(&FunctionList);
	if (ret) 
	{
		printf("fnGetList ERROR 0x%x", ret);
		return ret;
	}
#endif

	return ret;
}

void print_data(char *info, unsigned char *data, unsigned int len)
{
    int i = 0;
    if (info) printf("%s\n", info);

    for (i = 0; i < len; i++) {
        if (i && i % 16 == 0) printf("\n");
        printf("0x%02x ", data[i]);
    }
    printf("\n");
}

int get_device_info(HANDLE hdev)
{
    int ret = 0;
    DEVINFO info;

    memset(&info, 0, sizeof(info));
    ret = FunctionList->SKF_GetDevInfo(hdev, &info);
    if (ret) {
        printf("SKF_GetDevInfo() failed: %#x\n", ret);
        return ret;
    }

    printf("Manufacturer: %s\n", info.Manufacturer);
    printf("Issuer: %s\n", info.Issuer);
    printf("Label: %s\n", info.Label);
    printf("SerialNumber: %s\n", info.SerialNumber);

    return ret;
}
